<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\UserMill as UserMillModel;
use app\user\model\UserGroup as UserGroupModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Client as ClientModel;
use think\Db;

/**
 * 统计管理控制器
 * @package app\admin\controller
 */
class Stat extends Admin
{

    /**
     * 首页统计
     */
    public function ajaxIndex()
    {
        //所有客户
        $kh = Db::name('mill_client')->count();
        //所有工程
        $dd = Db::name('mill_order')->count();
        //所有销售额
        $je = 0;

        echo json_encode(array('kh' => $kh,'dd' => $dd,'je'=>$je));
    }

    /**
     * 订单阶段统计
     */
    public function ajaxOrderStatus()
    {
        //车间类型
        $mill_id = input('mill_id');
        //时间段 year:年 month:月 day:日
        $date = input('date');
        $series_type = input('series_type','line');
        $series_name = input('series_name','');
        //默认今天
        //$starttime = strtotime(date("Y-m-d", (time()-6*86400)));
        $starttime = strtotime(date("Y-m-d", (time())));
        $endtime = strtotime(date("Y-m-d 23:59:59", time()));

        if($date == 'year'){
            //本年
            $starttime = mktime(0,0,0,1,1,date('Y'));
            $endtime = strtotime('+1 year',$starttime) - 1;
        }
        elseif($date == 'month'){
            //本月
            $starttime = mktime(0,0,0,date('m'),1,date('Y'));
            $endtime = strtotime('+1 month',$starttime) - 1;
        }
        elseif($date == 'day'){
            //本日
            $starttime = strtotime(date('Y-m-d'));
            $endtime = strtotime('+1 day',$starttime) - 1;
        }

        $time_input = input('time');
        if(!empty($time_input)){
            $time_input = explode(' - ',$time_input);
            $starttime = strtotime($time_input[0]);
            $endtime = strtotime(date("Y-m-d 23:59:59", strtotime($time_input[1])));
        }

        $day = intval(($endtime+1-$starttime)/86400);

        $date = date('Y-m-d', $starttime);
        $end_date = date('Y-m-d 23:59:59', $endtime);

        //车间类型
        $status_where2 = "1";
        if($mill_id == 1){
            $user_ids = Db::name('admin_user')->where([['mill_id','<>',1]])->column('id');
            if(!empty($user_ids)){
                foreach ($user_ids as $uid){
                    $status_where2 .= " and g.status_flow not like '%|{$uid}\\_%' ";
                }
                $status_where2 = trim($status_where2,'and');
            }
            else $status_where2 .= " and 1<>1";
        }
        else if($mill_id == 2){
            $user_ids = Db::name('admin_user')->where(['mill_id'=>2])->column('id');
            if(!empty($user_ids)){
                $status_where2 .= " and (";
                foreach ($user_ids as $uid){
                    $status_where2 .= " g.status_flow like '%|{$uid}\\_%' or";
                }
                $status_where2 = trim($status_where2,'or').")";
            }
            else $status_where2 .= " and 1<>1";
        }
        else if($mill_id == 3){
            $user_ids = Db::name('admin_user')->where(['mill_id'=>3])->column('id');
            if(!empty($user_ids)){
                $status_where2 .= " and (";
                foreach ($user_ids as $uid){
                    $status_where2 .= " g.status_flow like '%|{$uid}\\_%' or";
                }
                $status_where2 = trim($status_where2,'or').")";
            }
            else $status_where2 .= " and 1<>1";
        }

        //开料
        $status1_where[] = ['g.status_flow','like','%\\_1|%'];
        $status1_where[] = ['g.status1_time','between time',[$date,$end_date]];
        $status1 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($status1_where)
            ->whereRaw($status_where2)
            ->find();

        //钣金
        $status2_where[] = ['g.status_flow','like','%\\_2|%'];
        $status2_where[] = ['g.status2_time','between time',[$date,$end_date]];
        $status2 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($status2_where)
            ->whereRaw($status_where2)
            ->find();

        //喷涂
        $status3_where[] = ['g.status_flow','like','%\\_3|%'];
        $status3_where[] = ['g.status3_time','between time',[$date,$end_date]];
        $status3 = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($status3_where)
            ->whereRaw($status_where2)
            ->find();

        if($mill_id){

            exit(json_encode(array('status1' => $status1,'status2' => $status2,'status3' => $status3,'series_type' => $series_type, 'date' => date('Y-m-d',$starttime).' - '.date('Y-m-d',$endtime))));
        }

        //$value_name = '订单阶段';
        //$value_title = ['开料', '钣金', '喷涂'];
        $value_title = ['开料'];
        $legend_data = ['产品数量 个', '总面积 M²'];
        $value = [
            [
                'name'              =>  '产品数量 个',
                'type'              =>  $series_type,
                'smooth'            =>  true,
                'data'              =>  [
                    floatval($status1['number_sum']),
                    //floatval($status2['number_sum']),
                    //floatval($status3['number_sum']),
                ],
                'itemStyle'         =>  [
                    'normal'        =>  [
                        'label'     =>  [
                            'show'  =>  true
                        ]
                    ]
                ]
            ],
            [
                'name'              =>  '总面积 M²',
                'type'              =>  $series_type,
                'smooth'            =>  true,
                'data'              =>  [
                    floatval($status1['area_sum']),
                    //floatval($status2['area_sum']),
                    //floatval($status3['area_sum']),
                ],
                'itemStyle'         =>  [
                    'normal'        =>  [
                        'label'     =>  [
                            'show'  =>  true
                        ]
                    ]
                ]
            ],
        ];
        echo json_encode(array('legend_data' => $legend_data,'series_type' => $series_type,'series_name' => $series_name,'value_title' => $value_title,'value' => $value, 'date' => date('Y-m-d',$starttime).' - '.date('Y-m-d',$endtime)));
    }

    /**
     * 客户阶段统计
     */
    public function ajaxClient()
    {

        $series_type = input('series_type','pie');
        $series_name = input('series_name','');

        //第一季度
        $starttime = strtotime(date('Y-01'));
        $endtime = strtotime('+3 month',$starttime)-1;
        $where1[] = ['create_time','between',[$starttime,$endtime]];
        $client1 = Db::name('mill_client')
            ->where($where1)
            ->count();
        //第二季度
        $starttime = strtotime('+3 month',$starttime);
        $endtime = strtotime('+3 month',$starttime)-1;
        $where2[] = ['create_time','between',[$starttime,$endtime]];
        $client2 = Db::name('mill_client')
            ->where($where2)
            ->count();
        //第三季度
        $starttime = strtotime('+3 month',$starttime);
        $endtime = strtotime('+3 month',$starttime)-1;
        $where3[] = ['create_time','between',[$starttime,$endtime]];
        $client3 = Db::name('mill_client')
            ->where($where3)
            ->count();
        //第四季度
        $starttime = strtotime('+3 month',$starttime);
        $endtime = strtotime('+3 month',$starttime)-1;
        $where4[] = ['create_time','between',[$starttime,$endtime]];
        $client4 = Db::name('mill_client')
            ->where($where4)
            ->count();

        //$value_name = '工程阶段';
        $value_title = [];
        $legend_data = ['第一季度','第二季度','第三季度','第四季度',];
        $value = [
            [
                'name'    =>  '客户年度统计',
                'type'    =>  $series_type,
                'radius'  =>  ['40%', '70%'],
                'center'  =>  ['35%', '50%'],
                'data'    =>  [
                    [
                        'name'      =>  '第一季度',
                        'value'     =>  floatval($client1),
                    ],
                    [
                        'name'      =>  '第二季度',
                        'value'     =>  floatval($client2),
                    ],
                    [
                        'name'      =>  '第三季度',
                        'value'     =>  floatval($client3),
                    ],
                    [
                        'name'      =>  '第四季度',
                        'value'     =>  floatval($client4),
                    ],
                ],
            ],
        ];
        echo json_encode(array('legend_data' => $legend_data,'series_type' => $series_type,'series_name' => $series_name,'value_title' => $value_title,'value' => $value));
    }

    /**
     * 发货数据统计
     */
    public function ajaxOrderJe()
    {
        //时间段 year:年 month:月 day:日
        $date = input('date');
        $series_type = input('series_type','line');
        $series_name = input('series_name');
        //默认今天
        //$starttime = strtotime(date("Y-m-d", (time()-6*86400)));
        $starttime = strtotime(date("Y-m-d", (time())));
        $endtime = strtotime(date("Y-m-d 23:59:59", time()));
        //时间差
        $day_time = 0;

        if($date == 'year'){
            //本年
            $starttime = mktime(0,0,0,1,1,date('Y'));
            $endtime = strtotime('+1 year',$starttime) - 1;

            //时间差
            $day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime));

            //x轴单位
            $series_name = '年';
        }
        elseif($date == 'month'){
            //本月
            $starttime = mktime(0,0,0,date('m'),1,date('Y'));
            $endtime = strtotime('+1 month',$starttime) - 1;

            //时间差
            $day_time = intval(($endtime+1-$starttime)/86400);

            //x轴单位
            $series_name = '月';
        }
        elseif($date == 'day'){
            //本日
            $starttime = strtotime(date('Y-m-d'));
            $endtime = strtotime('+1 day',$starttime) - 1;

            //时间差
            $day_time = intval(($endtime+1-$starttime)/86400);

            //x轴单位
            $series_name = '日';
        }
        else{

            //时间差
            $day_time = intval(($endtime+1-$starttime)/86400);

            //x轴单位
            $series_name = '日';
        }

        $time_input = input('time');
        if(!empty($time_input)){
            $time_input = explode(' - ',$time_input);
            $starttime = strtotime($time_input[0]);
            $endtime = strtotime(date("Y-m-d 23:59:59", strtotime($time_input[1])));

            //时间筛选超过3年，按年算
            if(date('Y',$endtime+1)-date('Y',$starttime)>3){

                //时间差
                $day_time = date('Y',$endtime+1)-date('Y',$starttime);
                $date = 'year';
                //x轴单位
                $series_name = '年';
            }
            //时间筛选超过2个月，按月算
            elseif(abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime))>3){

                //时间差
                $day_time = abs(date('Y',$endtime+1)-date('Y',$starttime)) * 12 + abs(date('m',$endtime+1)-date('m',$starttime));
                $date = 'month';
                //x轴单位
                $series_name = '月';
            }
            else{
                //时间差
                $day_time = intval(($endtime+1-$starttime)/86400);
                $date = 'day';
                //x轴单位
                $series_name = '日';
            }

        }

        while (1 <= $day_time) {

            //年
            if($date == 'year'){

                $new_date = date('Y-m-01', strtotime("-{$day_time} month",strtotime(date('Y-m-01',($endtime + 1)))));
                $end_date = date('Y-m-d H:i:s',strtotime("+1 month",strtotime($new_date))-1);

                $date_title = date('Y年m月',strtotime($new_date));
            }
            //月
            elseif($date == 'month'){

                $new_date = date('Y-m-d', strtotime("-{$day_time} day",($endtime + 1)));
                $end_date = date('Y-m-d H:i:s',strtotime("+1 day",strtotime($new_date))-1);

                $date_title = date('m月d日',strtotime($new_date));
            }
            //日
            else{
                $new_date = date('Y-m-d', strtotime("-{$day_time} day",($endtime + 1)));
                $end_date = date('Y-m-d H:i:s',strtotime("+1 day",strtotime($new_date))-1);

                $date_title = date('m月d日',strtotime($new_date));
            }

            //条件
            $where = [
                ['g.status','=',5],
                ['g.status5_time','between time',[$new_date,$end_date]]
            ];
            $address = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field('ceil(ifnull(sum(a.one_area),0)) as area_sum,count(g.id) as number_sum')
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->where($where)
                ->find();

            $transaction['num'][$date_title] = floatval($address['number_sum']);
            $transaction['area'][$date_title] = floatval($address['area_sum']);
            --$day_time;
        }

        $value_title = array_keys($transaction['num']);
        $legend_data = ['数量', '面积'];
        $value = [
            [
                'name'    =>  '数量',
                'type'    =>  $series_type,
                'smooth'  =>  true,
                'data'    =>  array_values($transaction['num']),
            ],
            [
                'name'    =>  '面积',
                'type'    =>  $series_type,
                'smooth'  =>  true,
                'data'    =>  array_values($transaction['area']),
            ],
        ];
        echo json_encode(array('legend_data' => $legend_data,'series_type' => $series_type,'series_name' => $series_name,'value_title' => $value_title,'value' => $value, 'date' => date('Y-m-d',$starttime).' - '.date('Y-m-d',$endtime)));

    }

    /**
     * 生产线进度统计
     */
    public function speed($archives_status=1)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $mill_id = input('mill_id');

        // 获取查询条件
        $map = $this->getMap();
        $map2 = 'g.status > 0 and ';
        //默认日期：今天
        $times[0] = strtotime(date('Y-m-d'));
        $times[1] = strtotime(date('Y-m-d 23:59:59'));

        if(!empty($map)){
            $m_v_i = 0;
            foreach ($map as &$m_v){
                if (in_array('times',$m_v)){
                    $times[0] = strtotime($m_v[2][0]);
                    $times[1] = strtotime($m_v[2][1]);
                    unset($map[$m_v_i]);
                }
                if (in_array('mill_id',$m_v)){
                    $mill_id = $m_v[2];
                    unset($map[$m_v_i]);
                }

                $m_v_i++;
            }
        }

        //dump(date('Y-m-d H:i:s',$times[0]));
        //dump(date('Y-m-d H:i:s',$times[1]));
        //exit;

        //车间类型
        $status_where2 = "1";
        if($mill_id == 1){
            $user_ids = Db::name('admin_user')->where([['mill_id','<>',1]])->column('id');
            if(!empty($user_ids)){
                foreach ($user_ids as $uid){
                    $status_where2 .= " and g.status_flow not like '%|{$uid}\\_%' ";
                }
                $status_where2 = trim($status_where2,'and');
            }
            else $status_where2 .= " and 1<>1";
        }
        else if($mill_id == 2){
            $user_ids = Db::name('admin_user')->where(['mill_id'=>2])->column('id');
            if(!empty($user_ids)){
                $status_where2 .= " and (";
                foreach ($user_ids as $uid){
                    $status_where2 .= " g.status_flow like '%|{$uid}\\_%' or";
                }
                $status_where2 = trim($status_where2,'or').")";
            }
            else $status_where2 .= " and 1<>1";
        }

        //生产状态：0待生产，1开料，2钣金，3喷涂，4复合
        $map2 .= " g.status  >= {$archives_status} and ";

        $map2 .= "(g.status{$archives_status}_time between {$times[0]} and {$times[1]})";

        $field = "o.*,{$archives_status} as archives_status,g.status as give_status2,FROM_UNIXTIME(g.status{$archives_status}_time,'%Y-%m-%d') as dates,count(g.id) as day_sum,sum(a.one_area) as area_day_sum";

        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field($field)
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($map)
            ->where($map2)
            ->whereRaw($status_where2)
            ->group('dates,g.order_id')
            ->order('dates asc,g.order_pid asc')
            ->select();

        $group_date = '';
        $data_list_new = [];
        $i = count($data_list)-1;
        //小计
        $day_sum = 0;
        $area_day_sum = 0;
        $number_sum = 0;
        $area_sum = 0;
        $number_ok_sum = 0;
        $area_ok_sum = 0;
        $number_no_sum = 0;
        $area_no_sum = 0;
        //合计
        $all_day_sum = 0;
        $all_area_day_sum = 0;
        $all_number_sum = 0;
        $all_area_sum = 0;
        $all_number_ok_sum = 0;
        $all_area_ok_sum = 0;
        if(!empty($data_list)){
            foreach ($data_list as $k=>$v){
                //按时间合计分组
                if(empty($group_date))$group_date = $v['dates'];

                //总数
                $where = ['order_id'=>$v['id']];
                $stat = Db::name('mill_order_archives')->field('sum(number) as number_sum,sum((number*one_area)) as area_sum')->where($where)->find();

                $v['number_sum'] = $stat['number_sum'];
                $v['area_sum'] = round($stat['area_sum'],4);

                //完成数
                //$where = [['g.order_id','=',$v['id']],['g.quality_status','>=',0],['g.status_flow','like',"%_{$archives_status}|%"]];
                $where = [['g.order_id','=',$v['id']],['g.quality_status','>=',0],['g.status','>=',$archives_status]];
                $stat_ok = Db::name('mill_order_archives_give')->alias('g')->field('count(g.id) as number_sum,sum(a.one_area) as area_sum')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->find();

                $v['number_ok_sum'] = $stat_ok['number_sum'];
                $v['area_ok_sum'] = round($stat_ok['area_sum'],4);

                //未完成数
                $v['number_no_sum'] = $v['number_sum']-$v['number_ok_sum'];
                $v['area_no_sum'] = $v['area_sum']-$v['area_ok_sum'];
                $v['area_no_sum'] = round($v['area_no_sum'],4);

                //跳转
                //read_type 1:日产产品明细 2:剩余产品明细
                /*$url_parm = "?_s=g.archives_sn={$v['archives_sn']}|times=".$v['dates'].urldecode(' - ').$v['dates']."&_o=g.archives_sn=like|times=between%20time";
                $v['day_sum_str'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$archives_status,'read_type'=>'1')).$url_parm.'">'.$v['day_sum'].'</a>';
                $url_parm = "?_s=g.archives_sn={$v['archives_sn']}&_o=g.archives_sn=like";
                $v['number_no_sum_str'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$archives_status,'read_type'=>'2')).$url_parm.'">'.$v['number_no_sum'].'</a>';*/
                $v['day_sum_str'] = '<a href="'.url('speedarchives',['id'=>$v['id'],'archives_status'=>$archives_status,'times'=>$v['dates']."%20-%20".$v['dates']]).'">'.$v['day_sum'].'</a>';
                $url_parm = "?_s=g.archives_sn={$v['archives_sn']}&_o=g.archives_sn=like";
                $v['number_no_sum_str'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$archives_status,'read_type'=>'2')).$url_parm.'">'.$v['number_no_sum'].'</a>';
                //喷涂部未生产跳转地址
                if($archives_status == 3)$v['number_no_sum_str'] = '<a href="'.url('speedarchives',['id'=>$v['id'],'archives_status'=>$archives_status,'read_type'=>'2']).'">'.$v['number_no_sum'].'</a>';


                //按时间合计分组
                if($group_date != $v['dates']){

                    //小计
                    $group_val = [
                        'id'                =>  0,
                        'engineering'       =>  "{$group_date} 小计",
                        'day_sum_str'       =>  $day_sum,
                        'area_day_sum'      =>  $area_day_sum,
                        'number_sum'        =>  $number_sum,
                        'area_sum'          =>  $area_sum,
                        'number_ok_sum'     =>  $number_ok_sum,
                        'area_ok_sum'       =>  $area_ok_sum,
                        'number_no_sum_str' =>  $number_no_sum,
                        'area_no_sum'       =>  $area_no_sum,
                        'create_time'       =>  0,
                    ];
                    $data_list_new[] = $group_val;

                    //重置
                    $day_sum = 0;
                    $area_day_sum = 0;
                    $number_sum = 0;
                    $area_sum = 0;
                    $number_ok_sum = 0;
                    $area_ok_sum = 0;
                    $number_no_sum = 0;
                    $area_no_sum = 0;
                    $group_date = $v['dates'];
                }

                //小计
                $day_sum += $v['day_sum'];
                $area_day_sum += $v['area_day_sum'];
                $number_sum += $v['number_sum'];
                $area_sum += $v['area_sum'];
                $number_ok_sum += $v['number_ok_sum'];
                $area_ok_sum += $v['area_ok_sum'];
                $number_no_sum += $v['number_no_sum'];
                $area_no_sum += $v['area_no_sum'];
                //合计
                $all_day_sum += $v['day_sum'];
                $all_area_day_sum += $v['area_day_sum'];
                $all_number_sum += $v['number_sum'];
                $all_area_sum += $v['area_sum'];
                $all_number_ok_sum += $v['number_ok_sum'];
                $all_area_ok_sum += $v['area_ok_sum'];

                $v['create_time'] = date('Y-m-d',$v['create_time']);


                //---------------------------------扫码人统计 start-------------------------------
                $v['user_nickname'] = '';

                $dates_start = strtotime($v['dates']);
                if($v['dates'] == date('Y-m-d',$times[1]))$dates_end = $times[1];
                else $dates_end = strtotime("{$v['dates']} 23:59:59");
                //生产状态：0待生产，1开料，2钣金，3喷涂，4复合
                $map3 = " g.status >= {$archives_status} ";

                $map4 = "(g.status{$archives_status}_time between {$dates_start} and {$dates_end})";

                //各车间扫码人
                $user_where = [['status','=',1]];
                if(!empty($mill_id))$user_where[] = ['mill_id','=',$mill_id];
                $user_ids = Db::name('admin_user')->where($user_where)->select();
                if(!empty($user_ids)){
                    foreach ($user_ids as $user_info){
                        //扫码人计件数
                        $map5 = " g.order_id = {$v['id']}";
                        $user_give_where = [
                            //['g.order_id','=',$v['id']],
                            ['g.status_flow','like',"%\\_{$archives_status}|{$user_info['id']}\\_%"],
                        ];
                        $user_info['give_count_day'] = Db::name('mill_order_archives_give')
                            ->alias('g')
                            ->where($map3)
                            ->where($map4)
                            ->where($map5)
                            ->where($user_give_where)
                            ->count('g.id');
                        $user_info['give_count'] = Db::name('mill_order_archives_give')
                            ->alias('g')
                            ->where($map3)
                            ->where($map4)
                            ->where($user_give_where)
                            ->count('g.id');
                        $user_info['give_count_day'] = floatval($user_info['give_count_day']);
                        $user_info['give_count'] = floatval($user_info['give_count']);

                        //如果扫码人计件数有，则组装显示
                        if(!empty($user_info['give_count_day'])){
                            //扫码人计件数
                            $v['user_nickname'] .= "{$user_info['nickname']}{$user_info['give_count_day']}/{$user_info['give_count']}，";
                            /*$group_val = [
                                'id'                =>  0,
                                'user_nickname'       =>  "{$user_info['nickname']}",
                                'user_day_sum_str'       =>  "{$user_info['give_count_day']}/{$user_info['give_count']}",
                            ];
                            $data_list_new[] = $group_val;*/
                        }
                    }
                }

                $v['user_nickname'] = trim($v['user_nickname'],'，');
                //---------------------------------扫码人统计 end---------------------------------

                $data_list_new[] = $v;
                //最后一条记录
                if($i == $k){

                    //小计
                    $group_val = [
                        'id'                =>  0,
                        'engineering'       =>  "{$group_date} 小计",
                        'day_sum_str'       =>  $day_sum,
                        'area_day_sum'      =>  $area_day_sum,
                        'number_sum'        =>  $number_sum,
                        'area_sum'          =>  $area_sum,
                        'number_ok_sum'     =>  $number_ok_sum,
                        'area_ok_sum'       =>  $area_ok_sum,
                        'number_no_sum_str' =>  $number_no_sum,
                        'area_no_sum'       =>  $area_no_sum,
                    ];
                    $data_list_new[] = $group_val;
                    //合计
                    $group_val = [
                        'id'                =>  0,
                        'engineering'       =>  "合计",
                        'day_sum_str'       =>  $all_day_sum,
                        'area_day_sum'      =>  $all_area_day_sum,
                        'number_sum'        =>  $all_number_sum,
                        'area_sum'          =>  $all_area_sum,
                        'number_ok_sum'     =>  $all_number_ok_sum,
                        'area_ok_sum'       =>  $all_area_ok_sum,
                    ];
                    $data_list_new[] = $group_val;
                }
            }
        }

        $columns = [ // 批量添加列
            ['dates', '日期'],
            ['archives_sn', '档案号'],
            ['engineering', '工程名称'],
            ['batch', '批次'],
            ['number_sum','总数量(件)'],
            ['area_sum','总面积(M²)'],
            ['create_time','下单日期'],
            ['day_sum_str','日产量(件)'],
            ['area_day_sum','日产面积(M²)'],
            ['number_ok_sum','总完成数量(件)'],
            ['area_ok_sum','总完成面积(M²)'],
            ['number_no_sum_str','未完成数量(件)'],
            ['area_no_sum','未完成面积(M²)'],
        ];
        $columns[] = ['user_nickname','扫码人'];
        $columns[] = ['right_button', '操作', 'btn'];

        //$status_arr = [1=>'开料',2=>'钣金',3=>'喷涂',4=>'复合'];
        $status_arr = GiveModel::$give_status;
        $title = '统计';
        if($archives_status)$title = $status_arr[$archives_status].$title;
        //JS
        $print_table_title = $status_arr[$archives_status]."每日产量报表 ".date('Y-m-d H:i:s',$times[0])." - ".date('Y-m-d H:i:s',$times[1]);
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var tr = $("#builder-table-head table thead").find("tr");
                        var colspan = tr.find("th").length-tr.find(".column-right_button").length;
                        var table_title = \'<tr><th colspan="\'+colspan+\'" style="font-size: 24px;font-weight: 600;">'.$print_table_title.'</th></tr>\';
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_title+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $mill_list = UserMillModel::getList();
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['select:2', 'mill_id', '车间','','',$mill_list],
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                //['daterange:2', 'times', '日期','',date('Y-m-d',$times[0]).' - '.date('Y-m-d',$times[1])],
                ['daterange:2', 'times', '日期', '', date('Y-m-d',$times[0]).' - '.date('Y-m-d',$times[1]), ['format' => 'YYYY-MM-DD HH:mm:ss','time-picker' => 'true', 'time-picker24-hour' => 'true', 'time-picker-seconds' => 'true']],
            ])
            ->addColumns($columns)
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            ->addRightButton('speedColor',['title' => '颜色统计','href' => url('speedColor',['id'=>'__id__','archives_status'=>$archives_status,'times'=>"__dates__%20-%20__dates__"]),'class'=>'btn btn-default disable-dch','icon'=>''])

            ->replaceRightButton(['id' => ['=','0']],'',['speedColor'])
            ->replaceRightButton(['archives_status' => ['<>',3]],'',['speedColor'])
            ->setRowList($data_list_new) // 设置表格数据
            ->setColumnWidth([
                'dates'  => 90,
                'archives_sn'  => 150,
                'engineering'  => 150,
                'batch'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 生产线产品明细
     */
    public function speedMore(){
        $input = input();
        $action = new Give();

        return $action->speed($input['archives_status'],$input['read_type']);
    }
    /**
     * 生产线产品
     */
    public function speedArchives(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $id = input('id');
        $archives_status = input('archives_status');
        $color = urldecode(input('color'));
        //read_type 1:已扫产品明细 2:剩余产品明细
        $read_type = input('read_type',0);
        $times_i = urldecode(input('times'));
        if(strpos($times_i,'%20-%20'))$times_i = urldecode($times_i);
        $times = explode(' - ',$times_i);
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.id','=',$id];

        if($color)$map[] = ['a.color','=',$color];
        if($read_type == 2)$map[] = ['g.status','between',[0,($archives_status-1)]];
        else $map[] = ['g.status_flow','like',"%\\_{$archives_status}|%"];

        //生产状态：0待生产，1开料，2钣金，3喷涂，4复合
        $map2 = " 1 ";

        if(!empty($times[0]) && !empty($times[1])){
            $times[0] = strtotime($times[0]);
            $times[1] = strtotime($times[1].' 23:59:59');
            $map2 .= " and (g.status{$archives_status}_time between {$times[0]} and {$times[1]})";
        }

        $archives_sn = Db::name('mill_order')->where(['id'=>$id])->value('archives_sn');

        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field("o.*,{$read_type} as read_type,{$archives_status} as archives_status,a.id as archives_id,a.model_sn,a.sort as archives_sort,a.color,group_concat(g.id) as give_ids,count(g.id) as number,sum(a.row_area) as row_area")
            ->where($map)
            ->where($map2)
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->leftJoin('mill_order_archives_give g','a.id=g.archives_id')
            ->group('a.id')
            ->orderRaw('convert(a.sort,signed) asc')
            ->paginate()
            ->each(function ($v){

                //已扫
                $give_where = [['g.id','in',$v['give_ids']],['g.status','>=',$v['archives_status']]];
                $ok = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number,sum(a.one_area) as row_area')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->find();
                $v['ok_num'] = $ok['number'];
                $v['ok_area'] = $ok['row_area'];
                //未扫
                $v['no_num'] = $v['number']-floatval($ok['number']);
                $v['no_area'] = $v['number']-floatval($ok['row_area']);

                return $v;
            })
        ;

        if(empty($times_i))$url_parm = "?_s=g.archives_sn={$archives_sn}&_o=g.archives_sn=like";
        else $url_parm = "?_s=g.archives_sn={$archives_sn}|times=".date('Y-m-d',$times[0])."%20-%20".date('Y-m-d',$times[1])."&_o=g.archives_sn=like|times=between%20time";
        // 使用ZBuilder快速创建数据表格
        $title = Db::name('mill_order')->where(['id'=>$id])->value("archives_sn")." 产品统计";
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案编号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['model_sn', '铝板编号'],
                ['archives_sort', '序号'],
                ['color', '颜色'],
                ['number','数量','callback',function($value, $data){

                    //read_type 1:已扫产品明细 2:剩余产品明细
                    $read_type = empty($data['read_type'])?1:$data['read_type'];
                    $url_parm = "?_s=g.archives_sn={$data['archives_sn']}|a.id={$data['archives_id']}&_o=g.archives_sn=like|a.color=eq";
                    $value = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$data['archives_status'],'read_type'=>$read_type)).$url_parm.'">'.$value.'</a>';

                    return $value;
                },'__data__'],
            ])
            ->setRowList($data_list) // 设置表格数据
            ->addTopButton('ablequality',['title' => '导出明细','href' => url('mill/stat/speedmore',['archives_status'=>$archives_status,'read_type'=>$read_type]).$url_parm,'class'=>'btn btn-default disable-dch','icon'=>''])
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 生产线产品颜色统计
     */
    public function speedColor(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $id = input('id');
        $archives_status = input('archives_status');
        $times_i = urldecode(input('times'));
        if(strpos($times_i,'%20-%20'))$times_i = urldecode($times_i);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.id','=',$id];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field("o.*,'{$times_i}' as times,{$archives_status} as archives_status,a.color,group_concat(a.id) as archives_ids,sum(a.number) as number,sum(a.row_area) as row_area")
            ->where($map)
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->group('a.color')
            ->order('a.color asc')
            ->paginate()
            ->each(function ($v){

                //已扫
                $give_where = [['g.archives_id','in',$v['archives_ids']],['g.status','>=',$v['archives_status']]];
                $ok = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number,sum(a.one_area) as row_area')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->find();
                $v['ok_num'] = $ok['number'];
                $v['ok_area'] = $ok['row_area'];
                //未扫
                $v['no_num'] = $v['number']-floatval($ok['number']);
                $v['no_area'] = $v['row_area']-floatval($ok['row_area']);

                //日产
                $day_where = $give_where;
                $times = explode(' - ',$v['times']);
                if(!empty($times[0]) && !empty($times[1])){
                    $times[0] = strtotime($times[0]);
                    $times[1] = strtotime($times[1].' 23:59:59');
                    $day_where[] = ["g.status{$v['archives_status']}_time",'between',"{$times[0]},{$times[1]}"];
                    //$map2 .= " and (g.status{$archives_status}_time between {$times[0]} and {$times[1]})";
                }
                $day = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number,sum(a.one_area) as row_area')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($day_where)
                    ->find();
                $v['day_num'] = $day['number'];
                $v['day_area'] = $day['row_area'];

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        $title = Db::name('mill_order')->where(['id'=>$id])->value("archives_sn")." 颜色统计";
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['color', '颜色'],
                ['number', '总数量'],
                ['row_area','总面积'],
                ['day_num','日产量'],
                ['day_area','日产面积'],
                ['ok_num','已扫数量','callback',function($value, $data){

                    /*//read_type 1:已扫产品明细 2:剩余产品明细
                    $url_parm = "?_s=g.archives_sn={$data['archives_sn']}|a.color={$data['color']}&_o=g.archives_sn=like|a.color=eq";
                    $value = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$data['archives_status'],'read_type'=>'1')).$url_parm.'">'.$value.'</a>';*/

                    //read_type 1:已扫产品明细 2:剩余产品明细
                    $value = '<a href="'.url('speedarchives',array('id'=>$data['id'],'color'=>$data['color'],'archives_status'=>$data['archives_status'],'read_type'=>'1')).'">'.$value.'</a>';

                    return $value;
                },'__data__'],
                ['ok_area', '已扫面积'],
                ['no_num','未扫数量','callback',function($value, $data){

                    /*//read_type 1:已扫产品明细 2:剩余产品明细
                    $url_parm = "?_s=g.archives_sn={$data['archives_sn']}|a.color={$data['color']}&_o=g.archives_sn=like|a.color=eq";
                    $value = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>$data['archives_status'],'read_type'=>'2')).$url_parm.'">'.$value.'</a>';*/

                    //read_type 1:已扫产品明细 2:剩余产品明细
                    $value = '<a href="'.url('speedarchives',array('id'=>$data['id'],'color'=>$data['color'],'archives_status'=>$data['archives_status'],'read_type'=>'2')).'">'.$value.'</a>';

                    return $value;
                },'__data__'],
                ['no_area', '未扫面积'],
            ])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 开料统计
     * @return mixed
     */
    public function cutting()
    {
        return $this->speed(1);
    }
    /**
     * 钣金统计
     * @return mixed
     */
    public function plate()
    {
        return $this->speed(2);
    }
    /**
     * 喷涂统计
     * @return mixed
     */
    public function spray()
    {
        return $this->speed(3);
    }
    /**
     * 复合统计
     * @return mixed
     */
    public function composite()
    {
        return $this->speed(4);
    }

    /**
     * 销售部统计
     * @return mixed
     */
    public function sales()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '销售统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $map_time = [['o.create_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.create_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }
        $title .= "{$starttime}-{$endtime}";
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('c.*,COUNT(DISTINCT c.id) as client_sum,COUNT(DISTINCT o.id) as order_sum,SUM(a.number) as number_sum,SUM(a.one_area*a.number) as area_sum,group_concat(DISTINCT o.id) as order_ids')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->leftJoin('mill_order_archives a','a.order_id=o.id')
            ->where($map)
            ->where($map_time)
            ->group('c.sales')
            ->order('order_sum desc,client_sum desc')
            ->paginate()
            ->each(function ($v){

                //完成数
                $v['area_ok_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where([['g.order_id','in',$v['order_ids']],['g.quality_status','>=',0],['g.status','>=',3]])
                    ->sum('a.one_area');

                $v['area_sum'] = round($v['area_sum'],4);
                $v['area_ok_sum'] = round($v['area_ok_sum'],4);

                $v['area_no_sum'] = $v['area_sum']-$v['area_ok_sum'];
                $v['area_no_sum'] = round($v['area_ok_sum'],4);

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('销售统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'c.sales', '销售经理名称', 'like'],
                ['daterange:2', 'o.create_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['sales', '销售经理名称'],
                ['client_sum', '总客户数量'],
                ['order_sum', '总工程数量'],
                ['number_sum', '产品总单数'],
                ['area_sum','总面积 M²'],
                ['area_ok_sum','已完成面积 M²'],
                ['area_no_sum','未完成面积 M²'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            ->addRightButton('client',['title' => '查看客户','href' => url('mill/index/client').'?_s=c.sales=__sales__&_o=sales=like','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->addRightButton('index',['title' => '查看工程','href' => url('mill/order/index').'?_s=c.sales=__sales__&_o=sales=like','data-files'=>'archivesEdit','class'=>'btn btn-default disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 设计部统计
     * @return mixed
     */
    public function archives()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '设计统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $map_time = [['o.archives_sign_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.archives_sign_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }
        $title .= "{$starttime}-{$endtime}";
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,COUNT(DISTINCT o.id) as client_sum,COUNT(DISTINCT o.id) as order_sum,SUM(a.number) as number_sum,SUM(a.one_area*a.number) as area_sum,SUM(a.one_area*a.number) as area_sum,group_concat(DISTINCT a.id) as archives_ids')
            ->leftJoin('mill_order_archives a','a.order_id=o.id')
            ->leftJoin('mill_order_archives_give g','g.archives_id=a.id')
            ->where($map)
            ->where($map_time)
            ->group('o.archives_plan')
            ->order('order_sum desc,client_sum desc')
            ->paginate()
            ->each(function ($v){

                //完成数
                $v['area_ok_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number_sum,sum(a.one_area) as area_sum')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where([['a.id','in',$v['archives_ids']],['g.quality_status','>=',0],['g.status','>=',3]])
                    ->sum('a.one_area');
                $v['area_no_sum'] = $v['area_sum']-$v['area_ok_sum'];

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('设计统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'o.archives_plan', '计师名称', 'like'],
                ['daterange:2', 'o.archives_sign_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['archives_plan', '设计师名称'],
                ['order_sum', '面积表总数'],
                ['number_sum', '产品总数量'],
                ['area_sum','总面积 M²'],
                ['area_ok_sum','已完成面积 M²'],
                ['area_no_sum','未完成面积 M²'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            ->addRightButton('client',['title' => '查看客户','href' => url('mill/index/client').'?_s=o.archives_plan=__archives_plan__&_o=o.archives_plan=like','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->addRightButton('index',['title' => '查看工程','href' => url('mill/order/index').'?_s=o.archives_plan=__archives_plan__&_o=o.archives_plan=like','data-files'=>'archivesEdit','class'=>'btn btn-default disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 发货部统计
     * @return mixed
     */
    public function deliver()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '发货统计';
        // 获取查询条件
        $map = $this->getMap();
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $map_time = [['g.address_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'g.address_time'){
                    $map_time = [$v];
                    $starttime = date('Y-m-d',strtotime($v[2][0]));
                    $endtime = date('Y-m-d',strtotime($v[2][1]));
                    unset($map[$k]);
                }
            }
        }
        $title .= "{$starttime}-{$endtime}";

        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("'' as show_i,group_concat(DISTINCT g.order_id) as order_ids,g.car_id,g.status5_time,g.address_time,g.address_date,g.address_sn,g.address_status")
            ->where($map)
            ->where($map_time)
            ->where("g.status=5 and g.address_status in (1,2)")
            ->group("g.address_sn")
            ->order('g.address_sn desc')
            ->paginate()
            ->each(function ($v){

                $order = Db::name('mill_order')
                    ->alias('o')
                    ->field('o.*,group_concat(DISTINCT o.order_sn) as order_sn,group_concat(DISTINCT o.batch) as batch,sum(a.number) as number_sum,sum(a.row_area) as area_sum')
                    ->leftJoin('mill_order_archives a','a.order_id=o.id')
                    ->where([['o.id','in',$v['order_ids']]])
                    ->find();
                $v['order_sn'] = $order['order_sn'];
                $v['batch'] = $order['batch'];
                $v['archivees_sn'] = "{$order['order_sn']}[{$order['batch']}]";
                $v['client_id2'] = $order['client_id'];
                $v['plate_number'] = Db::name('mill_car')->where([['id','=',$v['car_id']]])->value('plate_number');

                $v = array_merge($order,$v);

                //总数
                $v['area_sum'] = round($v['area_sum'],4);
                //已扫
                $give_where = [['g.address_sn','=',$v['address_sn']]];
                $ok = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number,sum(a.one_area) as row_area')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->find();
                $v['ok_num'] = $ok['number'];
                $v['ok_area'] = $ok['row_area'];


                //未扫
                $give_where = [['g.order_id','in',$v['order_ids']],['g.status','<',5]];
                $no = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('count(g.id) as number,sum(a.one_area) as row_area')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->find();
                $v['no_num'] = $no['number'];
                $v['no_area'] = round($no['row_area'],4);

                $v['ok_num_str'] = '<a href="'.url('mill/order/deliverGiveShow'.$v['show_i'],['address_sn' => $v['address_sn']]).'">'.$v['ok_num'].'</a>';
                $v['no_num_str'] = '<a href="'.url('mill/order/deliverGiveShow'.$v['show_i'],['order_ids'=>$v['order_ids'],'address_sn'=>$v['address_sn'],'not_address'=>1]).'">'.$v['no_num'].'</a>';

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('发货统计') // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'g.archives_sn', '档案号', 'like'],
                ['daterange:2', 'g.address_time', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['plate_number', '车牌号码'],
                ['address_sn', '发货单号'],
                ['status5_time', '日期','datetime'],
                ['archivees_sn', '档案号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum','总数量(件)'],
                ['area_sum','总面积(M²)'],
                ['ok_num_str','已发货数量'],
                ['ok_area','已发货面积'],
                ['no_num_str','未发货数量'],
                ['no_area','未发货面积'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            ->addRightButton('deliverShow',['title' => '查看明细','href' => url('mill/order/deliverShow',['address_sn' => '__address_sn__','status'=>'5']),'class'=>'btn btn-primary disable-dch','icon'=>''])
            ->addRightButton('delivergiveshow3',['title' => '导出明细','href' => url('mill/order/deliverGiveShow3',['address_sn' => '__address_sn__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 生产部统计
     * @return mixed
     */
    public function give($is_status = true)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '生产统计';
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.status','=',1];
        $color = '';
        //默认12个月
        $starttime = strtotime('-1 year',strtotime(date('Y-m-d')));
        $endtime = strtotime(date('Y-m-d 23:59:59'));
        $starttime = '';
        $endtime = '';
        /*$map_time = [['o.archives_sign_time','between',"{$starttime},{$endtime}"]];
        $starttime = date('Y-m-d',$starttime);
        $endtime = date('Y-m-d',$endtime);*/

        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'o.archives_sign_time'){
                    $map_time = [$v];
                    $starttime = strtotime(date('Y-m-d',strtotime($v[2][0])));
                    $endtime = strtotime(date('Y-m-d 23:59:59',strtotime($v[2][1])));
                    unset($map[$k]);
                }
                elseif($v[0] == 'aa.color'){
                    $color = trim($v[2],'%');
                }
            }
        }
        //$title .= "{$starttime}-{$endtime}";

        if($is_status)$is_status = ' and (aa.status<6)';
        else $is_status = '';

        if($starttime && $endtime)$map[] = ['o.archives_sign_time','between',"{$starttime},{$endtime}"];
        $map = array_merge($map);

        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field("o.*,aa.color")
            ->leftJoin('mill_order_archives aa','aa.order_id=o.id '.$is_status)//查找还处于发货完的产品
            ->where($map)
            //->where($map_time)
            ->where('aa.id IS NOT NULL')
            ->group('o.id,aa.color')
            ->order('o.status_time desc,o.archives_sign_time desc')
            ->paginate()
            ->each(function ($v){

                $archvices_where = [
                    ['a.order_id','=',$v['id']],
                    ['a.color','like',$v['color']],
                ];
                $archvices = ArchivesModel::getOneStat('','','',$archvices_where);
                $v = array_merge($v,$archvices);

                //跳转
                //read_type 1:日产产品明细 2:剩余产品明细
                $url_parm = "?_s=g.archives_sn={$v['archives_sn']}|a.color={$v['color']}&_o=g.archives_sn=like|a.color=like";
                $v['status1'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>1,'read_type'=>'1')).$url_parm.'">'.$v['status1'].'</a>';
                $v['status1_no'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>1,'read_type'=>'2')).$url_parm.'">'.$v['status1_no'].'</a>';

                $v['status2'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>2,'read_type'=>'1')).$url_parm.'">'.$v['status2'].'</a>';
                $v['status2_no'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>2,'read_type'=>'2')).$url_parm.'">'.$v['status2_no'].'</a>';

                $v['status3'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>3,'read_type'=>'1')).$url_parm.'">'.$v['status3'].'</a>';
                $v['status3_no'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>3,'read_type'=>'2')).$url_parm.'">'.$v['status3_no'].'</a>';

                $v['status4'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>4,'read_type'=>'1')).$url_parm.'">'.$v['status4'].'</a>';
                $v['status4_no'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>4,'read_type'=>'2')).$url_parm.'">'.$v['status4_no'].'</a>';

                $v['status5'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>5,'read_type'=>'1')).$url_parm.'">'.$v['status5'].'</a>';
                $v['status5_no'] = '<a href="'.url('mill/stat/speedmore',array('archives_status'=>5,'read_type'=>'2')).$url_parm.'">'.$v['status5_no'].'</a>';

                return $v;
            })
        ;

        //合计
        $order_ids = Db::name('mill_order')
            ->alias('o')
            ->field("o.*")
            ->leftJoin('mill_order_archives aa','aa.order_id=o.id and (aa.status<6)')//查找还处于发货完的产品
            ->where($map)
            //->where($map_time)
            ->where('aa.id IS NOT NULL')
            ->group('o.id')
            ->column('o.id');
        if(!empty($order_ids)){
            $order_ids = implode(',',$order_ids);

            $archvices_where = [['a.order_id','in',$order_ids]];
            if($color)$archvices_where[] = ['a.color','like',$color];
            $archvices_where = array_merge($archvices_where);

            $archvices = ArchivesModel::getOneStat('','','',$archvices_where);

            $info = [
                'id'            =>  0,
                'archives_sn'   =>  '',
                'archives_sign_time'   =>  '',
                'batch'  =>  '合计'
            ];
            $info = array_merge($info,$archvices);

            $data_list_arr = $data_list;

            foreach($data_list_arr as $key=>$value){
                $new_key = $key+1;
                if($key == 0)$data_list[$key] = $info;
                $data_list[$new_key] = $value;
            }

        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    var wrapper_height = $("#builder-table-wrapper").css("max-height");
                    wrapper_height = parseInt(wrapper_height) + 30;
                    $("#builder-table-wrapper").css("max-height",wrapper_height+"px");
                    var table_head_html = \'<tr>\' +
                        \'<th colspan="1">档案号</th>\' +
                        \'<th colspan="1">项目名称</th>\' +
                        \'<th colspan="1">批次</th>\' +
                        \'<th colspan="1">颜色</th>\' +
                        \'<th colspan="1">产品总量</th>\' +
                        \'<th colspan="1">面积</th>\' +
                        \'<th colspan="1">经办人</th>\' +
                        \'<th colspan="4">开料</th>\' +
                        //\'<th colspan="4">钣金</th>\' +
                        //\'<th colspan="4">喷涂</th>\' +
                        //\'<th colspan="4">复合</th>\' +
                        \'<th colspan="4">发货</th>\' +
                        //\'<th colspan="1">审核日期</th>\' +
                        \'<th colspan="1">来图日期</th>\' +
                        \'<th colspan="1" class="disable-dch">操作</th>\' +
                        \'</tr>\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    //固定右侧
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    $("#builder-table-right-body").css("margin-top","100px");
                    var right_height = $("#builder-table-right").css("height");
                    right_height = parseInt(right_height) + 50;
                    $("#builder-table-right").css("height",right_height+"px");
                    
                    //固定左侧
                    $("#builder-table-left-head table thead").html(table_head_html+$("#builder-table-left-head table thead").html());
                    var left_height = $("#builder-table-left").css("height");
                    left_height = parseInt(left_height) + 50;
                    $("#builder-table-left").css("height",left_height+"px");
                            
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('生产统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'o.archives_handle', '经办人', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'aa.color', '颜色', 'like'],
                ['daterange:2', 'o.archives_sign_time', '来图日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', ''],
                ['engineering', ''],
                ['batch', ''],
                ['color',''],
                ['number_sum', ''],
                ['area_sum',''],
                ['archives_handle',''],
                ['status1','已开料'],
                ['status1_no','未开料'],
                ['status1_area_sum','已开面积'],
                ['status1_area_on_sum','未开面积'],
                //['status2','完成钣金'],
                //['status2_no','未完成钣金'],
                //['status2_area_sum','完成面积'],
                //['status2_area_on_sum','未完成面积'],
                //['status3','已喷涂'],
                //['status3_no','未喷涂'],
                //['status3_area_sum','已喷涂面积'],
                //['status3_area_on_sum','未喷涂面积'],
                //['status4','已复合'],
                //['status4_no','未复合'],
                //['status4_area_sum','已复合面积'],
                //['status4_area_on_sum','未复合面积'],
                ['status5','已发'],
                ['status5_no','未发'],
                ['status5_area_sum','已发面积'],
                ['status5_area_on_sum','未发面积'],
                //['status_time','','date'],
                ['archives_sign_time','','date'],
                ['right_button', '', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->fixedLeft(5)
            ->fixedRight(1)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            ->addRightButton('cutting',['title' => '明细','href' => url('mill/give/cutting').'?_s=g.status=0|g.archives_sn=__archives_sn__&_o=g.status=eq|g.archives_sn=like','class'=>'btn btn-primary disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'archives_sn'  => 170,
                'batch'  => 170,
                'engineering'  => 170,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 生产部统计
     * @return mixed
     */
    public function give2(){

        return $this->give(false);
    }
    /**
     * 看板
     * @return mixed
     */
    public function urgent()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '看板';
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['g.status','<',3];
        $map[] = ['g.id','<>',''];
        $map[] = ['g.quality_status','>=','0'];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field("o.*")
            ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
            ->where($map)
            ->group('o.id')
            ->order('o.status_time desc,o.archives_sign_time desc')
            ->select()
        ;

        foreach ($data_list as &$v){
            $where = [['order_id','=',$v['id']]];
            $v['number_sum'] = Db::name('mill_order_archives')->where($where)->sum('number');
            $where[] = ['quality_status','>=',0];
            $v['status1'] = Db::name('mill_order_archives_give')->where($where)->where('status1_time > 0')->count();
            $v['status1_no'] = $v['number_sum']-$v['status1'];
            $v['status2'] = Db::name('mill_order_archives_give')->where($where)->where('status2_time > 0')->count();
            $v['status2_no'] = $v['number_sum']-$v['status2'];
            $v['status3'] = Db::name('mill_order_archives_give')->where($where)->where('status3_time > 0')->count();
            $v['status3_no'] = $v['number_sum']-$v['status3'];
        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    
                    //全屏
                    $("[data-action=\'fullscreen_toggle\']").click();
                    $(".tab-content").css("padding","0 20px");
                    //宽高
                    $("#builder-table-body").css("max-height",($(document.body).height()-74));
                    $("#builder-table-body").css("margin-top","30px");
                    $("#builder-table-head").css("position","fixed");
                    $("#builder-table-head").css("top","0");
                    //颜色
                    $(".table-striped,.table-builder th").css("background-color","#333333");
                    $(".table-striped,.table-builder th").css("color","#ffffff");
                    $(".table-striped,.table-builder th").css("font-size","59px");
                    
                    $(".table-striped,.table-builder tr").css("background-color","#333333");
                    $(".table-striped,.table-builder tr").css("color","#7aff00");
                    $(".table-striped,.table-builder tr").css("font-size","70px");
                    
                    //滚动事件
                    var mybox=$("#builder-table-body");
                    var myTimer;
                    var speed=40;//速度毫秒 值越小速度越快
                    var stepSpeed=2;//滚动像素 值越大越快
                    //向下	
                    var nowPos=mybox[0].scrollTop;//当前值
                    var maxPos=mybox[0].scrollHeight - mybox.outerHeight();//最大值
                    changePos(mybox,nowPos,maxPos);
                    
                    function changePos(box,from,to){
                        if(myTimer){window.clearInterval(myTimer);}
                        var temStepSpeed=stepSpeed;
                        if(from>to){
                            myTimer=window.setInterval(function(){
                                    var boxScrollTop = box[0].scrollTop;
                                    if(box[0].scrollTop>to){
                                        box[0].scrollTop-=temStepSpeed;
                                    }
                                    //已滑动到顶部
                                    if(boxScrollTop <= box[0].scrollTop){
                                        window.clearInterval(myTimer);
                                    }
                                },speed);
                        }else if(from<to){
                            myTimer=window.setInterval(function(){
                                    var boxScrollTop = box[0].scrollTop;
                                    if(box[0].scrollTop<to){
                                        box[0].scrollTop += temStepSpeed;
                                    }
                                    //已滑动到底部
                                    if(boxScrollTop >= box[0].scrollTop){
                                        window.clearInterval(myTimer);
                                        $(".page-reload").click();
                                    }
                                },speed);
                        }
                    }

                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('生产统计') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->addColumns([ // 批量添加列
                ['order_sn', '档案号'],
                ['engineering', '项目名称'],
                ['batch', '批次'],
                ['number_sum', '数量'],
                ['urgent_status_time', '要求出货时间','date'],
                ['urgent_status','生产状态','callback',function($value){
                    $arr = [0=>'正常',1=>'加急',2=>'特急'];
                    $class = '';
                    switch ($value) {
                        case '0': $class = 'info';break;
                        case '1': $class = 'warning';break;
                        case '2': $class = 'primary';break;
                    }
                    $status = '<span class="label label-'.$class.'">'.$arr[$value].'</span>';

                    return $status;
                },'__data__'],
                //['status1_no','开料未完成'],
                ['status2_no','钣金未完成'],
                ['status3_no','喷涂未完成'],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->setHeight('auto')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    /**
     * 生产统计
     * @return mixed
     */
    public function schedul($status = 1)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $title = '生产计划';
        // 获取查询条件
        $map = $this->getMap();
        //$status = 1;
        //默认日期：今天
        $times[0] = strtotime(date('Y-m-d'));
        $times[1] = strtotime(date('Y-m-d 23:59:59'));

        if(!empty($map)){
            $m_v_i = 0;
            foreach ($map as &$m_v){
                if (in_array('times',$m_v)){
                    $times[0] = strtotime($m_v[2][0]);
                    $times[1] = strtotime($m_v[2][1]);
                    unset($map[$m_v_i]);
                }
                elseif (in_array('status',$m_v)){
                    $status = $m_v[2];
                    unset($map[$m_v_i]);
                }

                $m_v_i++;
            }
        }
        $map = array_merge($map);
        $starttime = date('Y-m-d',$times[0]);
        $endtime = date('Y-m-d',$times[1]);

        $data_list = [];

        //小计
        $status_sum = 0;
        $status_area_sum = 0;
        //合计
        $all_status_sum = 0;
        $all_status_area_sum = 0;

        $day_i = (($times[1]+1)-$times[0])/86400;
        for ($i=0;$i<$day_i;$i++){
            //按天分组查询
            $day_start = $times[0] + ($i*86400);
            $day_end = strtotime(date('Y-m-d 23:59:59',$day_start));
            $day = date('Y-m-d',$day_start);

            $map2 = "o.status{$status}_time between {$day_start} and {$day_end}";

            $order_id1 = Db::name('mill_order_archives_give')
                ->alias('o')
                ->where($map)
                ->where($map2)
                ->column('DISTINCT o.order_id');

            $map2 = "a.status < {$status} and o.give_status > 0";
            $order_id2 = Db::name('mill_order_archives')
                ->alias('a')
                ->where($map)
                ->where($map2)
                ->leftJoin('mill_order o','o.id=a.order_id')
                ->column('DISTINCT a.order_id');

            $map2 = "(o.give_status = {$status} and o.start_time between {$day_start} and {$day_end}) or (o.end_time between {$day_start} and {$day_end}) ";
            $order_id3 = Db::name('mill_order_plan')
                ->alias('o')
                ->where($map)
                ->where($map2)
                ->where("o.delete = 1")
                ->column('DISTINCT o.order_id');
            $order_ids = array_unique(array_merge($order_id1,$order_id2,$order_id3));

            $order_id_delete = Db::name('mill_order_plan')
                ->alias('o')
                ->where($map)
                ->where($map2)
                ->where("o.delete = 0")
                ->column('DISTINCT o.order_id');

            if(!empty($order_id_delete)){
                foreach ($order_id_delete as $del_id){
                    if(($key = array_search($del_id,$order_ids))){
                        unset($order_ids[$key]);
                    }
                }
            }
            $order_ids = implode(',',$order_ids);

            if(!empty($order_ids)){
                $map2 = "o.id in({$order_ids}) and o.give_status > 0";
                $order_list = Db::name('mill_order')
                    ->alias('o')
                    ->where($map)
                    ->where($map2)
                    ->select();
            }

            if(!empty($order_list)){
                foreach ($order_list as &$v){

                    $v['dates'] = $day;

                    $archvices = ArchivesModel::getOneStat($v['id'],'order_id','eq','',[$day_start,$day_end],$status);

                    $v = array_merge($v,$archvices);

                    //小计
                    $status_sum += $v['status_sum'];
                    $status_area_sum += $v['status_area_sum'];
                    //合计
                    $all_status_sum += $v['status_sum'];
                    $all_status_area_sum += $v['status_area_sum'];

                    $data_list[] = $v;
                }

                //小计
                $group_val = [
                    'id'    =>  '',
                    'area_sum'       =>  "小计",
                    'status_sum'           =>  $status_sum,
                    'status_area_sum'  =>  $status_area_sum,
                    'create_time'       =>  0,
                ];
                $data_list[] = $group_val;

                //重置
                $status_sum = 0;
                $status_area_sum = 0;

            }

        }
        if(!empty($data_list)){

            //合计
            $group_val = [
                'id'    =>  '',
                'area_sum'       =>  "合计",
                'status1'           =>  $all_status_sum,
                'status1_area_sum'  =>  $all_status_area_sum,
                'create_time'       =>  0,
            ];
            $data_list[] = $group_val;
        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                            
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $give_status_search = GiveModel::$give_status_search;
        unset($give_status_search[0]);
        unset($give_status_search[1]);
        unset($give_status_search[4]);
        unset($give_status_search[5]);
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['select:2', 'status', '排期','',$status,$give_status_search],
                ['text:2', 'o.archives_sn', '档案号', 'like'],
                ['daterange:2', 'times', '日期','',"{$starttime} - {$endtime}"],
            ])
            ->addColumns([ // 批量添加列
                ['dates', '日期'],
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum','总面积'],
                ['status_sum','日产量'],
                ['status_area_sum','日产面积'],
                ['number_ok_sum','总完成数量'],
                ['area_ok_sum','总完成面积'],
                ['number_on_sum','未完成数量'],
                ['area_on_sum','未完成面积'],
                ['right_button', '操作', 'btn']
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('plan',['title' => '计划单','href' => url('mill/order/plan',['give_status'=>$status]),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '55%'], 'title' => ['计划单', 'font-size:24px;text-align: center;']])
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->addRightButton('deliverShow',['title' => '删除计划','href' => url('mill/order/planDel',['order_id'=>'__id__','archives_sn'=>'__archives_sn__','give_status'=>$status,'starttime'=>$starttime,'endtime'=>$endtime]),'class'=>'btn btn-primary disable-dch ajax-get confirm','icon'=>''])
            ->replaceRightButton(['id'=>['=','']],'')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板

    }
    /**
     * 开料生产统计
     * @return mixed
     */
    public function schedulCutting()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->schedul(1);
    }
    /**
     * 钣金生产统计
     * @return mixed
     */
    public function schedulPlate()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->schedul(2);
    }
    /**
     * 喷涂生产统计
     * @return mixed
     */
    public function schedulSpray()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->schedul(3);
    }
    /**
     * 复合生产统计
     * @return mixed
     */
    public function schedulComposite()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->schedul(3);
    }
}
